package com.lovo.pis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.pis.dto.PageBean;
import com.lovo.pis.dto.PowerBean;
import com.lovo.pis.dto.RoleBean;
import com.lovo.pis.dto.UserBean;
import com.lovo.pis.mapper.RoleMapper;
import com.lovo.pis.mapper.UserMapper;
import com.lovo.pis.service.IRoleService;
import com.lovo.pis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.RoleList;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleBean> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public IPage<RoleBean> queryAll(PageBean<RoleBean> pageInfo) {
        return roleMapper.selectPage(new Page<>(pageInfo.getCurPage(), pageInfo.getPageSize()), null);
    }

    @Override
    public List<RoleBean> queryAllRoleName() {
        return roleMapper.selectList(null);
    }

    @Override
    public List<PowerBean> queryPowerName(List<Integer> roleIdList) {
        List<RoleBean> roleList = roleMapper.selectPowerName(roleIdList);
        List<PowerBean> powerList = new ArrayList<>();
        for (RoleBean roleBean : roleList) {
            for (PowerBean powerBean : roleBean.getPowerList()) {
                if (!powerList.contains(powerBean)) {
                    powerList.add(powerBean);
                }
            }
        }
        return powerList;
    }

    @Override
    public RoleBean queryById(int id) {
        return roleMapper.selectRole(id);
    }

    @Override
    @Transactional
    public boolean changeById(RoleBean roleBean) {
        //清空权限
        roleMapper.deletePower(roleBean.getId());
        //添加权限
        List<Integer> list = new ArrayList<>();
        for (PowerBean powerBean : roleBean.getPowerList()) {
            list.add(powerBean.getId());
        }
        roleMapper.insertPower(roleBean.getId(),list);
        return true;
    }

    @Override
    @Transactional
    public void addRole(RoleBean roleBean) {
        //添加角色
        roleMapper.insert(roleBean);
        int roleId = roleBean.getId();
        //添加关联表
        List<Integer> list = new ArrayList<>();
        for (PowerBean powerBean : roleBean.getPowerList()) {
            list.add(powerBean.getId());
        }
        roleMapper.insertPower(roleId,list);
    }

    @Override
    @Transactional
    public void removeById(int id) {
        //删除角色关联表
        roleMapper.deletePower(id);
        //删除角色
        roleMapper.deleteById(id);
    }


}
